using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace TheLogWatcher
{
    public class LogFileProvider
    {
        public LogFileProvider(string filename, bool multiFile)
        {
            if (!multiFile)
            {
                this.CreateSingleFileName(filename);
            }
            else
            {
                this.CreateSplitFileNames(filename);
            }
        }

        private string originalFilename;

        /// <summary>
        ///     The original source filename of the log file.
        /// </summary>
        public string OriginalFilename
        {
            get { return originalFilename; }
            set { originalFilename = value; }
        }

        private LogFile[] logFiles;

        /// <summary>
        ///     All log files used in current log message report.
        /// </summary>
        public LogFile[] LogFiles
        {
            get { return logFiles; }
            set { logFiles = value; }
        }

        private int currentFileIndex = 0;

        /// <summary>
        ///     Gets the next file, no matter what file handling is activated.
        ///     <b>NOTE:</b>
        ///     When this method returns NULL, all files have been returned before.
        ///     Use <code>ResetFileIterator</code> to begin at start.
        /// </summary>
        /// <returns></returns>
        public LogFile GetNextFile()
        {
            // Check if single file or multiple files exist.
            if (this.logFiles != null && this.currentFileIndex < this.logFiles.Length)
            {
                LogFile logFile = this.logFiles[this.currentFileIndex];
                this.currentFileIndex++;
                return logFile;
            }
            return null;
        }

        /// <summary>
        ///     Returns the log file that contains entries of
        ///     the specified message type or NULL.
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public LogFile GetLogFile(MessageTypes type)
        {
            if (this.logFiles != null)
            {
                // There is only one file containing all log entries
                if (this.logFiles.Length == 1 && this.logFiles[0].MessageTypeInLogFile == MessageTypes.UNDEFINED)
                {
                    return this.logFiles[0];
                }

                // Searches a log file with the specified message type.
                for (int i = 0; i < this.logFiles.Length; i++)
                {
                    LogFile logFile = this.logFiles[i];
                    if (logFile.MessageTypeInLogFile == type)
                    {
                        return logFile;
                    }
                }
            }
            return null;
        }

        /// <summary>
        ///     This method is important when <code>GetNextFile</code> is used.
        ///     When beginning with the first file is required, this must be called.
        /// </summary>
        public void ResetFileIterator()
        {
            this.currentFileIndex = 0;
        }

        private void filesExistingCheck(string[] filenames)
        {
            for (int i = 0; i < filenames.Length; i++)
            {
                if (File.Exists(filenames[i]))
                {
                    Console.WriteLine("File < " + filenames[i] + " > already exists and will be overwritten.");
                }
            }
        }

        /// <summary>
        ///     Creates a log file name for a single file.
        /// </summary>
        /// <param name="filename"></param>
        private void CreateSingleFileName(string filename)
        {
            this.logFiles = new LogFile[1];
            LogFile logFile = new LogFile(filename);
            logFile.MessageTypeInLogFile = MessageTypes.UNDEFINED;
            this.logFiles[0] = logFile;
        }

        /// <summary>
        ///     If multi-file splitting is activated there will be built new files.
        ///     The names are created here.
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private void CreateSplitFileNames(string filename)
        {
            if (filename == null)
            {
                return;
            }
            // Find extension point
            string baseExt = null;
            int ext = filename.LastIndexOf('.');
            if (ext == -1 || ext < (filename.Length - 5))
            {
                // This could be processed if filename has no extension
                ext = filename.Length;
            }
            else
            {
                baseExt = filename.Substring(ext);
            }
            string baseFile = filename.Substring(0, ext);

            // Check if currently file was already splitted
            bool alreadySplitted = false;
            for (int i = 0; i < MessageType.Length(); i++)
            {
                if (baseFile.EndsWith(Constants.SplitFileSeparator + MessageType.StringArray()[i]))
                {
                    alreadySplitted = true;
                    break;
                }
            }

            if (alreadySplitted)
            {
                DialogResult result = MessageBox.Show("The selected file seems to be\npart of an already splitted file.\nDo really want to split it again ?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
                if (result == DialogResult.Cancel)
                {
                    this.CreateSingleFileName(filename);
                    return;
                }
            }

            // Set filenames
            this.logFiles = new LogFile[MessageType.Length()];
            for (int i = 0; i < MessageType.Length(); i++)
            {
                string outputFile = baseFile + Constants.SplitFileSeparator + MessageType.StringArray()[i] + baseExt;
                LogFile logFile = new LogFile(outputFile);
                logFile.MessageTypeInLogFile = MessageType.MessageTypeAt(i);
                this.logFiles[i] = logFile;
            }
        }
    }
}
